<template>
  <div class="modle goods" v-show="show">
    <div class="tit"><b>精选商品</b></div>
    <div class="info flex-btw">
      <span>展示数量：</span>
    </div>
    <div class="box">
      <div
        :class="[{ on: styleNum == 1 }, ' css_box flex-column']"
        @click="chooseStyle('goods', 1)"
      >
        <div class="css css1">
          <span class="block"></span>
        </div>
        <div>样式一</div>
      </div>
      <div
        :class="[{ on: styleNum == 2 }, ' css_box flex-column']"
        @click="chooseStyle('goods', 2)"
      >
        <div class="css css2">
          <span class="block" v-for="i in 2" :key="i"></span>
        </div>
        <div>样式二</div>
      </div>
      <div
        :class="[{ on: styleNum == 3 }, ' css_box flex-column']"
        @click="chooseStyle('goods', 3)"
      >
        <div class="css css3">
          <span class="block"></span>
          <span class="block"></span>
          <span class="block"></span>
        </div>
        <div>样式三</div>
      </div>
    </div>
    <div class="content">
      <div :class="['part', { 'border-error' : item.error}]" v-for="(item, index) in list" :key="item.id">
        <div class="goods">
          <div class="goods-box flex-middle">
            <span class="">标题名称：</span>
            <el-input
              class="wid220"
              v-model="item.name"
              placeholder="专题名称"
              maxlength="6"
              show-word-limit
              :disabled="item.link_type == 2 || item.link_type == 3"
            ></el-input>
          </div>
          <div class="goods-box flex-middle mg-t-10">
            <span>商品来源：</span>
            <el-select v-model="item.link_type" class="wid220">
              <el-option
                v-for="source in sourceOptions"
                :key="source.value"
                :label="source.label"
                :value="source.value"
              ></el-option>
            </el-select>
          </div>
          <div class="goods-box flex-middle mg-t-10">
            <span></span>
            <!-- 一级分类 -->
            <el-select
              class="wid220"
              v-model="item.category"
              v-show="item.link_type == 2"
              @change="changeCategory($event, item)"
            >
              <el-option
                v-for="item in category"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              ></el-option>
            </el-select>
            <!-- 二级分类 -->
            <el-cascader
              class="wid220"
              v-model="item.categoryValue"
              v-show="item.link_type == 3"
              :options="category"
              :props="{
                expandTrigger: 'hover',
                value: 'id',
                label: 'title',
                children: 'selfNext',
              }"
              @change="changeCategory($event, item)"
            >
            </el-cascader>
            <!-- 添加商品 -->
            <div
              class="add flex-center"
              v-show="item.link_type == 1"
              @click="selectGoods(null, index)"
            >
              <i class="el-icon-plus"></i>
            </div>
          </div>
          <template v-if="item.link_type == 1">
            <div class="goods_box">
              <div
                class="good"
                v-for="(good, goodindex) in item.commodity_list"
                :key="goodindex"
              >
                <div
                  class="img_box"
                  @click="selectGoods(good.id, [index,goodindex])"
                >
                  <img class="img" :src="good.img" />
                  <div class="change flex-center">更换商品</div>
                </div>
                <div class="name flex-middle">{{ good.name }}</div>
                <div
                  class="remove flex-center"
                  @click="remove(goodindex, item.commodity_list)"
                >
                  移除
                </div>
                <div
                  class="sort flex-column"
                  :style="
                    goodindex == 0 || goodindex == item.commodity_list.length - 1
                      ? 'justify-content:center;'
                      : ''
                  "
                >
                  <img
                    v-show="goodindex != 0"
                    @click="Move(goodindex, 'up', item.commodity_list)"
                    src="@/assets/images/shop_up.png"
                  />
                  <img
                    v-show="goodindex != item.commodity_list.length - 1"
                    @click="Move(goodindex, 'down', item.commodity_list)"
                    src="@/assets/images/shop_down.png"
                  />
                </div>
              </div>
            </div>
          </template>
        </div>
        <div class="operation">
          <div class="delete" @click="remove(index, list)">
            <img
              src="https://copartner.oss-cn-beijing.aliyuncs.com/logo/2405/21/Hd7tNvIYGGYiscscsB9FkNlzSeVsV5rpcV2bRKdx.png"
              alt=""
            />
          </div>
          <div class="move flex-column-between">
            <img
              v-show="index != 0"
              @click="Move(index, 'up', list)"
              src="@/assets/images/shop_up.png"
            />
            <img
              v-show="index != list.length - 1"
              @click="Move(index, 'down', list)"
              src="@/assets/images/shop_down.png"
            />
          </div>
        </div>
        <div class="error-msg" v-if="item.error">{{ item.errorMsg }}</div>
      </div>
      <div class="part addGoods">
        <div class="goods">
          <div class="goods-box flex-middle">
            <span class="">标题名称：</span>
            <el-input
              class="wid220"
              v-model="addGoodsForm.name"
              placeholder="专题名称"
              maxlength="6"
              show-word-limit
              :disabled="addGoodsForm.link_type == 2 || addGoodsForm.link_type == 3"
            ></el-input>
          </div>
          <div class="goods-box flex-middle mg-t-10">
            <span>商品来源：</span>
            <el-select
              v-model="addGoodsForm.link_type"
              class="wid220"
            >
              <el-option
                v-for="source in sourceOptions"
                :key="source.value"
                :label="source.label"
                :value="source.value"
              ></el-option>
            </el-select>
          </div>
          <div class="goods-box flex-middle mg-t-10">
            <span></span>
            <!-- 一级分类 -->
            <el-select
              class="wid220"
              v-model="addGoodsForm.category"
              v-show="addGoodsForm.link_type == 2"
              @change="changeCategory($event, addGoodsForm, 'add')"
            >
              <el-option
                v-for="item in category"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              ></el-option>
            </el-select>
            <!-- 二级分类 -->
            <el-cascader
              class="wid220"
              v-model="addGoodsForm.categoryValue"
              v-show="addGoodsForm.link_type == 3"
              :options="category"
              :props="{
                expandTrigger: 'hover',
                value: 'id',
                label: 'title',
                children: 'selfNext',
              }"
              @change="changeCategory($event, addGoodsForm, 'add')"
            >
            </el-cascader>
            <!-- 添加商品 -->
            <div
              class="add flex-center"
              v-show="addGoodsForm.link_type == 1"
              @click="selectGoods(null, 'add')"
            >
              <i class="el-icon-plus"></i>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="flex-center">
      <div class="submit flex-center" @click="submit()">保存</div>
    </div>
  </div>
</template>

<script>
import { packApi } from "@/utils/public";
import { findCategory } from "@/utils/index";
import { getRecommendCommodity, saveRecommendCommodity } from "@/api/shop/shop";
const defaultForm = {
  name: "",
  link_type: "",
  category: "",
  categoryValue: [],
  commodity_list: [],
}
export default {
  props: ["show", "styleNum", "category"],
  data() {
    return {
      goodsInfo: [], // img:'',id:'',name:'',
      list: [],
      sourceOptions: [
        {
          label: "自定义商品",
          value: 1,
        },
        {
          label: "商品一级分类",
          value: 2,
        },
        {
          label: "商品二级分类",
          value: 3,
        },
      ], // 商品来源
      addGoodsForm: {
        name: "",
        link_type: "",
        category: "",
        categoryValue: [],
        commodity_list: [],
      },
    };
  },
  created() {
    this.getCommodity();
  },
  methods: {
    // 获取商品
    getCommodity() {
      getRecommendCommodity(packApi()).then(res=> {
        if(res.errcode == 0) {
          this.$emit("chooseStyle", "goods", res.data.style);
          this.list = res.data.subject_list.map(item=> {
            if(item.link_type == 3) item.categoryValue = [item.pid,item.category_id]
            if(item.link_type == 2) item.category = item.category_id;
            return {
              category: "",
              categoryValue: [],
              error: false,
              errorMsg: "",
              ...item,
            }
          });
        } else {
          this.$message.error(res.errmsg);
        }
      })
    },
    changeCategory(e, form, type = null) {
      let id = Array.isArray(e) ? e[1]: e;
      let info = findCategory(id, this.category);
      form.name = info.title;
      if(type == "add") {
        this.list.push(this._.cloneDeep(form));
        const formKeys = Object.keys(defaultForm);
        this.$nextTick(()=> {
          for (let key of formKeys) {
            form[key] = defaultForm[key];
          }
        })
      }
    },
    chooseStyle(name, style) {
      this.$emit("chooseStyle", name, style);
    },
    selectGoods(id, index) {
      if(index == "add" && !this.addGoodsForm.name) return this.$message.error("请先设置标题名称");
      let radio = id ? true : false;
      this.$emit("selectGoods", { id, index, ref: "refGoods", isRadio: radio });
    },
    getSelectedGood(index, info) {
      if(index == "add") {
        let newgoods = info.map((item) => {
          return {
            img: item.pic,
            id: item.id,
            name: item.name,
          };
        });
        this.addGoodsForm.commodity_list = newgoods;
        this.list.push(this._.cloneDeep(this.addGoodsForm));
        const formKeys = Object.keys(defaultForm);
        for (let key of formKeys) {
          this.addGoodsForm[key] = defaultForm[key];
        }
        return;
      }
      if(Array.isArray(index)) {
        const listItem = this.list[index[0]];
        if (listItem && Array.isArray(listItem.commodity_list)) {
          let idx = listItem.commodity_list.findIndex(item=> item.id == info.id);
          if(idx != -1) return this.$message.error("该商品已存在");
          const goods = listItem.commodity_list[index[1]];
          if (goods) {
            // 合并更新字段
            goods.img = info.pic;
            goods.id = info.id;
            goods.name = info.name;
          }
        }
      } else {
        let newgoods = info.map((item) => {
          return {
            img: item.pic,
            id: item.id,
            name: item.name,
          };
        });
        let allgoods = this.list[index].commodity_list.concat(newgoods);
        let seen = new Set(); // 使用 Set 来记录已经出现过的商品ID
        let filterGoods = []; // 用于存放去重后的商品列表
        for (let i = 0; i < allgoods.length; i++) {
          // 如果当前商品的 ID 没有出现在 seen 中
          if (!seen.has(allgoods[i].id)) {
            seen.add(allgoods[i].id); // 将商品的 ID 加入到 seen 中
            filterGoods.push(allgoods[i]); // 将当前商品添加到 filterGoods 数组
          }
        }
        this.list[index].commodity_list = filterGoods;
      }
    },
    remove(index, list) {
      this.$confirm("删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          list.splice(index, 1);
        })
        .catch(() => {});
    },
    //移动排序
    Move(index, type, list) {
      let toIndex = type === "up" ? index - 1 : index + 1;
      // 检查目标索引是否越界
      if (toIndex < 0 || toIndex >= list.length) return;  // 如果超出范围，直接返回
      // 交换元素位置
      const [item] = list.splice(index, 1);  // 删除索引位置的元素
      list.splice(toIndex, 0, item);  // 将该元素插入到目标位置
    },
    submit() {
      let errorFound = false;
      for(let item of this.list) {
        // 重置 error 和 errorMsg
        item.error = false;
        item.errorMsg = "";
        // 如果之前已经找到错误，直接退出循环
        if(errorFound) return;
        // 检查专题名称是否为空
        if(!item.name) {
          item.error = true;
          item.errorMsg = "请输入专题名称";
          errorFound = true; // 标记错误，停止继续检查后续项
        } else if(item.link_type == 1 && !item.commodity_list.length) {
          // 检查如果 link_type 为 1，则商品列表是否为空
          item.error = true;
          item.errorMsg = "请添加商品";
          errorFound = true; // 标记错误，停止继续检查后续项
        } else if((item.link_type == 2 && !item.category) || (item.link_type == 3 && !item.categoryValue.length)) {
          // 检查如果 link_type 为 2 或 3，分类是否未选择
          item.error = true;
          item.errorMsg = "请选择分类";
          errorFound = true; // 标记错误，停止继续检查后续项
        }
      }
      // 如果找到错误，直接返回
      if(errorFound) return;
      this.listLoading = true;
      let subject_list = this.list.map(item=> {
        if(item.link_type == 3) item.category = Array.isArray(item.categoryValue) ? item.categoryValue[1] : item.categoryValue;
        return {
          name: item.name,
          link_type: item.link_type,
          commodity_id: item.commodity_list.length ? item.commodity_list.map(commodity=> commodity.id).join(",") : "",
          category_id: item.category,
        }
      })
      let data = {
        style: this.styleNum,
        subject_list: JSON.stringify(subject_list),
        name: "精选商品",
      }
      saveRecommendCommodity(packApi(data)).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          this.$message.success("保存成功");
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.goods {
  font-size: 14px;
  padding-right: 60px !important;
  .box {
    margin-bottom: 30px;
    .css_box {
      width: 248px;
      height: 158px;
      margin-top: 12px;
      border: 1px solid #d1d1d1;
      background: #fff;
      justify-content: center;
      align-items: center;
      &.on {
        border-color: #19b098;
      }
      + .css_box {
        margin-left: 20px;
      }
      .css {
        width: 100%;
        height: 110px;
        padding: 0 20px;
        .block {
          background: #03a98e;
        }
      }
      .css1 {
        display: flex;
        align-items: center;
        justify-content: space-around;
        .block {
          width: 140px;
          height: 74px;
        }
      }
      .css2 {
        padding: 0 30px;
        display: flex;
        align-items: center;
        justify-content: center;
        .block {
          width: 63px;
          height: 74px;
          + .block {
            margin-left: 7px;
          }
        }
      }
      .css3 {
        display: flex;
        align-items: center;
        justify-content: center;
        .block {
          margin-right: 7px;
          width: 43px;
          height: 55px;
        }
        .right_b {
          display: flex;
          flex-direction: column;
          .block {
            width: 83px;
            height: 34px;
            + .block {
              margin-top: 7px;
            }
          }
        }
      }
    }
  }
  .content {
    .part {
      position: relative;
      padding: 20px;
      background: #fff;
      margin-bottom: 14px;
      border: 1px solid transparent;
      .titimg_box {
        position: relative;
        .titimg_btn {
          position: absolute;
          top: 0;
          width: 100%;
          height: 20px;
          background: #19b098;
          color: #fff;
          font-size: 10px;
          cursor: pointer;
        }
        .img {
          width: 100%;
          height: 100%;
        }
        &.noimg {
          border: 2px dashed #d3d3d3;
        }
      }
      .goods-box {
        margin-left: 15px;
        font-size: 14px;
        color: #666666;
        span {
          display: block;
          width: 75px;
        }
        .add {
          width: 60px;
          height: 60px;
          border: 2px solid #d3d3d3;
          color: #d3d3d3;
          font-size: 20px;
        }
      }
      .goods {
        // display: flex;
        background: #fff;
        min-width: 500px;
        // padding: 30px 0px;
          .goods_box {
            margin: 10px 0 10px 90px;
            .good {
              display: flex;
              .img_box {
                position: relative;
                box-sizing: border-box;
                width: 60px;
                height: 60px;
                .img {
                  border: 1px solid #19b098;
                  width: 60px;
                  height: 60px;
                }
                .change {
                  width: 100%;
                  position: absolute;
                  bottom: 0;
                  left: 0;
                  right: 0;
                  color: #fff;
                  background: #19b098;
                  font-size: 10px;
                  padding: 1px 0;
                }
              }
              .name {
                width: 154px;
                height: 60px;
                background: #e1f3f0;
                border-top: 1px solid #19b098;
                border-bottom: 1px solid #19b098;
                padding-left: 20px;
                color: #404040;
                font-size: 14px;
              }
              .remove {
                width: 26px;
                height: 60px;
                background: #d81e1e;
                color: #fff;
                writing-mode: vertical-lr;
              }
              .sort {
                justify-content: space-between;
                margin-left: 20px;
              }
              & + .good {
                margin-top: 10px;
              }
            }
          }
      }
      .operation {
        position: absolute;
        top: 0;
        right: -30px;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        img {
          width: 20px;
          height: 20px;
        }
        .move {
          img:nth-child(2) {
            margin-top: 10px;
          }
        }
      }
    }
    .border-error {
      border-color: #ff0000;
      margin-bottom: 20px;
      position: relative;
    }
    .error-msg {
      position: absolute;
      bottom: -20px;
      left: 0;
      color: #ff0000;
      font-size: 12px;
    }
  }
}
</style>